# utils/network.py: 获取客户端IP地址（get_client_ip）
import re
from ipaddress import ip_address, IPv4Address, IPv6Address
from django.core.exceptions import SuspiciousOperation


def get_client_ip(request) -> str:
    """
    安全获取客户端真实IP（防X-Forwarded-For伪造）
    支持IPv4/IPv6，通过反向代理验证

    """
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '')
    remote_addr = request.META.get('REMOTE_ADDR', '127.0.0.1')

    # 分割并清洗代理链
    proxies = [ip.strip() for ip in x_forwarded_for.split(',') if ip.strip()]

    # 安全验证逻辑
    valid_ips = []
    for ip in proxies + [remote_addr]:
        try:
            # 验证IP格式
            if not re.match(r'^([0-9a-fA-F.:]+)$', ip):
                continue

            parsed_ip = ip_address(ip)
            if parsed_ip.is_private or parsed_ip.is_loopback:
                continue

            valid_ips.append(str(parsed_ip))
        except ValueError:
            continue

    # 返回首个有效IP或最终REMOTE_ADDR
    return valid_ips[0] if valid_ips else remote_addr


# IP白名单验证扩展
def validate_ip_security(ip: str) -> bool:
    """验证IP是否在允许范围内"""
    from django.conf import settings
    if ip in settings.ALLOWED_IPS:
        return True
    if any(ip.startswith(prefix) for prefix in settings.ALLOWED_IP_PREFIXES):
        return True
    return False
